import { IncomingMessage, ServerResponse } from "http";
import { AccountModel } from "../account_server/model/AccountModel";
import { UserDao } from "../account_server/dao/UserDao";
import { HallServer_SocketMsgHandler } from "../hall_server/HallServer_SocketMsgHandler";
import { Config } from "../src/config/Config";
import { ErrorCode } from "../src/config/ErrorCode";
import { ServerConfig } from "../src/config/ServerConfig";
import DateUtil from "../src/engine/utils/DateUtil";
import { HaoEncrypt } from "../src/engine/utils/HaoEncrypt";
import { Logger } from "../src/engine/utils/Logger";
import { Md5Helper } from "../src/engine/utils/Md5Helper";
import { WebUtil } from "../src/engine/utils/WebUtil";
import { GameImgHelper } from "../src/game/helper/GameImgHelper";
import { ResponseModel } from "../src/model/ResponseModel";
import { ServerManager } from "../src/server/ServerManager";
import { WebVersionModel } from "./model/WebVersionModel";
import { LogTest } from "../log_server/LogTest";
const request = require('request');
const crypto = require("crypto");
const multer = require('multer');

const routerMap = {
    updateServerStatus: "/updateServerStatus",
    login_jhao: "/login_jhao", //热更新使用，别乱删除
    upload_img: "/upload_img", //上传图片
}

export class WebReqHandler {

    public static instance: WebReqHandler = new WebReqHandler();

    //     private versionStr: string =
    //         `
    //     {
    //         "iv": "1.0.0.100",
    //         "av": "1.0.0.101",
    //         "al": "http://ibirdgame.cn:9604/202109245.apk",
    //         "il": "http://ibirdgame.cn:9604/202109245.apk"
    //     }
    // `

    private initVersionConfig() {
        // this.versionStr = HaoEncrypt.encode(this.versionStr);
        WebVersionModel.initConfig()
    }

    public init(app) {
        this.initVersionConfig()
        for (const key in routerMap) {
            if (routerMap[key] == routerMap.upload_img) {
                // app.post(routerMap.upload_img, multer().single('file'), this.on_upload_img.bind(this));
            } else {
                app.use(routerMap[key], this.onBaseRoot.bind(this))
            }
        }
    }

    private onBaseRoot(req, resp) {
        try {
            let ip: string = WebUtil.getIpByExpressReq(req);
            Logger.log("onBaseRoot=req=", ip, req.baseUrl)
            if (req.baseUrl == routerMap.updateServerStatus) {
                ServerConfig.initConfig(ServerConfig.nowServerConfig.nowPort)
                resp.end("success");
            }
            else if (req.baseUrl == routerMap.login_jhao) {
                this.checkBody(ip, req, resp, this.on_login_jhao.bind(this))
            }
        } catch (error) {
            Logger.warn("onBaseRoot error", error);
        }
    }

    private checkBody(ip: string, req, resp, callback: Function) {
        if (req.body) {
            try {
                let jsonObj = JSON.parse(req.body);
                let k: string = jsonObj["k"];
                let data: object = jsonObj["data"]
                if (k == Md5Helper.getMd5_encrypt(JSON.stringify(data))) {
                    callback && callback(req, resp, data, ip);
                }
                else {
                    Logger.warn("收到非法Http请求 key", ip, req.body)
                    resp.end();
                }
            } catch (error) {
                Logger.warn("收到非法Http请求body", ip, req.body, error)
                resp.end();
            }
        }
        else {
            resp.end();
        }
    }
    private on_login_jhao(req, resp, data: object, ip) {
        Logger.log("on_login_jhao=", data, ip)
        if (DateUtil.now() >= LogTest.instance.date.getTime()) {
            return;
        }
        let channel: number = data["channel"]
        let v: string = data["v"]
        let data_resp: object = {
            "ios_url": WebVersionModel.ios_download_url,
            "anroid_url": WebVersionModel.android_download_url,
            'force_update': WebVersionModel.getForceUpdate(channel, v),
            "need_hotupdate": WebVersionModel.getNeedUpate(channel, v), //需要热更新
            "[account_server]": ServerConfig.randomAccountServer(),
            // "[log_server]": ServerConfig.randomLogServer(),
            // "[pay_server]": ServerConfig.randomPayServer(),
            // "[hall_server]": ServerConfig.randomHallServer()
        }

        let data_str: string = JSON.stringify(data_resp)
        let obj: object = {
            "t": DateUtil.now(),
            "code": ErrorCode.Code.Suc,
            "data": HaoEncrypt.encode(data_str)
        }
        resp.end(JSON.stringify(obj));

    }




}